<template>
  <div class="artcile-list">
    <van-pull-refresh
      :success-text="num"
      success-duration="1000"
      v-model="isLoading"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <articleItem
          v-for="(item, index) in list"
          :key="index"
          :articleItem="item"
        >
        </articleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { getArticles } from '@/api/article'
import articleItem from '../article-item/index'
export default {
  name: 'articleList',
  props: ['channel'],
  data() {
    return {
      list: [],
      isLoading: false,
      error: false,
      loading: false,
      finished: false,
      timestamp: null,
      num: ''
    }
  },
  methods: {
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        this.list.unshift(...data.data.results)
        this.isLoading = false
        this.num = `更新${data.data.results.length}条数据`
      } catch (err) {
        this.isLoading = false
        this.num = '刷新失败'
      }
    },
    async onLoad() {
      // 异步更新数据
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        if (results.length) {
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  },
  components: { articleItem }
}
</script>
<style lang="less" scoped>
.artcile-list {
  height: 79vh;
  overflow: auto;
}
</style>
